package com.myproject.user.interceptor;

import java.net.URLDecoder;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;

import org.apache.struts2.StrutsStatics;

import com.myproject.user.action.DesEncrypter;
import com.myproject.user.model.User;
import com.myproject.user.model.UserCookie;
import com.myproject.user.service.UserService;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.interceptor.Interceptor;

public class AuthenticationInterceptor implements Interceptor {

	private static final long serialVersionUID = 5686161301032864561L;
	
	private UserService userService;
	
	private User user;
    private UserCookie userCookie;

	private String userName;

 
	@Override
	public void destroy() {		
	}

	@Override
	public void init() {		
	}

	@Override
	public String intercept(ActionInvocation actionInvocation) throws Exception {
		
		Map<String, Object> session = actionInvocation
				.getInvocationContext().getSession();
		HttpServletRequest request = (HttpServletRequest)actionInvocation.getInvocationContext()
					.get(StrutsStatics.HTTP_REQUEST);
		
		user = (User)session.get("user");
		
		
		if(user == null){
			Cookie[] cookies = request.getCookies();
			if(cookies != null){
				for (Cookie cookie : cookies) {
					if (cookie.getName().equals("MYJSESSIONID")){
						String encryptedCookieValue = cookie.getValue();
						
						Map<String, Object> eqRestrictions = new HashMap<String, Object>();
						eqRestrictions.put("idUserCookie", encryptedCookieValue);
						
						userCookie = (UserCookie)userService.GetUniqueModelData(UserCookie.class, eqRestrictions);  
						
						if(userCookie != null){
							user = userCookie.getUser();
							DesEncrypter decrypter = new DesEncrypter( ((ActionSupport)
									actionInvocation.getAction()).getText("cookiePass"));
		                    String cookieValue = decrypter.decrypt(URLDecoder.decode(encryptedCookieValue,"UTF-8"));
		                    userService.AlterEvent("DELETE_USER_COOKIE_" + cookieValue, "WEEK");
							session.put("user", user);
							String userFullName = user.getUserProfile().getUserFirstName() + " "
			    					+ user.getUserProfile().getUserLastName1() + " " 
			    					+ ((user.getUserProfile().getUserLastName2() == null) ? "" : user.getUserProfile().getUserLastName2());
			    			session.put("userFullName",userFullName);
							return actionInvocation.invoke();
						}
					}
				}
			}
			
			return ActionSupport.LOGIN;
		}
		return actionInvocation.invoke();
		
	}
	 
	public UserService getUserService() {
		return userService;
	}

	public void setUserService(UserService userService) {
		this.userService = userService;
	}

	public String getUserName() {
		return userName;
	}

	public void setUserName(String userName) {
		this.userName = userName;
	}
	
	

}
